﻿using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api;
using DocumentFormat.OpenXml.Office2010.Excel;
using JinfuyuanProject.AliPayDemo;
using JinfuyuanProject.Entity;
using JinfuyuanProject.Entity.Filter;
using JinfuyuanProject.Entity.ViewModels;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using Aop.Api.Util;
using JinfuyuanProject.Service.Interface;
using DotNet.Utilities;
using System.Configuration;
using JinfuyuanProject.Service;


namespace JinfuyuanProject.Controllers
{
    /*
* 合同列表页
* 母子涵
* 2025-04-24
*/
    public class ContractController : Controller
    {
        private readonly IContractService _contractService;
        private readonly IPackageService _packageService;
        private readonly JinfuyuanDbContext _db;
        private readonly IServiceDoService _serviceDoService;

        public ContractController(IContractService contractService, IPackageService packageService, JinfuyuanDbContext db, IServiceDoService serviceDoService)
        {
            _contractService = contractService;
            _packageService = packageService;
            _db = db;
            _serviceDoService = serviceDoService;
        }
        // GET: Contract
        #region 视图
        public ActionResult Index()
        {

            return View();
        }
        public ActionResult ContractList()
        {

            List<Package> packages = _packageService.GetList().ToList();
            ViewBag.Packages = packages;
            return View();
        }
        public ActionResult ContractPay(int Id = 0)
        {
            ViewBag.Id = Id;
            return View();
        }
        public ActionResult PayChack()
        {

            return View();
        }
        //支付宝支付
        public ActionResult PayPage(ContractVM contractVM)
        {
            DefaultAopClient client = new DefaultAopClient(config.gatewayUrl, config.app_id, config.private_key, "json", "1.0", config.sign_type, config.alipay_public_key, config.charset, false);
            // 外部订单号，商户网站订单系统中唯一的订单号
            string out_trade_no = $"{contractVM.Id}_{DateTime.Now:yyyyMMddHHmmssfff}";
            // 订单名称
            string subject = Request.QueryString["ParturientName"] + "的订单";
            // 付款金额 套餐+押金
            string pmoney = Request.QueryString["PackagePrice"];
            string Deposit = Request.QueryString["Deposit"];
            decimal depositAmount = Convert.ToDecimal(Deposit);
            decimal packagePrice = Convert.ToDecimal(pmoney);
            decimal totalAmount = depositAmount + packagePrice;
            string total_amout = totalAmount.ToString("F2");
            // 商品描述
            string body = "锦福缘母婴湾套餐";
            // 支付中途退出返回商户网站地址
            string quit_url = ConfigurationManager.AppSettings["quitUrl"];
            // 组装业务参数model
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.Body = body;
            model.Subject = subject;
            model.TotalAmount = total_amout;
            model.OutTradeNo = out_trade_no;
            model.ProductCode = "QUICK_WAP_WAY";
            model.QuitUrl = quit_url;
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            // 设置支付完成同步回调地址
            request.SetReturnUrl(ConfigurationManager.AppSettings["SetReturnUrl"]);
            // 设置支付完成异步通知接收地址
            // request.SetNotifyUrl("");
            // 将业务model载入到request
            request.SetBizModel(model);
            AlipayTradeWapPayResponse response = null;
            try
            {
                response = client.pageExecute(request, null, "post");
                Response.Write(response.Body);
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return View();
        }
        //支付校验
        public ActionResult AlipayNotify()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            Dictionary<string, string> sArray = GetRequestGet();
            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV1(sArray, config.alipay_public_key, config.charset, config.sign_type, false);
                if (flag)
                {
                    Response.Write("同步验证通过");
                    decimal total_amount = Convert.ToDecimal(sArray["total_amount"]);
                    string out_trade_no = sArray["out_trade_no"];
                    Staff staff = Session["user"] as Staff;
                    int sid = staff.Id;
                    int contractId = int.Parse(out_trade_no.Split('_')[0]); // 合同ID
                    _contractService.PaySuccess(contractId, total_amount, sid, 0);
                   
                }
                else
                {
                    Response.Write("同步验证失败");
                }
            }
            return View();
        }
        public Dictionary<string, string> GetRequestGet()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll;
            //coll = Request.Form;
            coll = Request.QueryString;
            String[] requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            }
            return sArray;
        }
        #endregion
        #region 接口
        public JsonResult GetContractList(int page, int limit, ContractVM contractVM)
        {
            ContractFilter contractFilter = new ContractFilter();
            contractFilter.limit = limit;
            contractFilter.page = page;
            contractFilter.ParturientName = contractVM.ParturientName;
            contractFilter.ParturientPhone = contractVM.ParturientPhone;
            contractFilter.PackageID = contractVM.PackageId;
            return Json(_contractService.Query(contractFilter), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetPayDetail(int id)
        {
            return Json(_contractService.GetPay(id));
        }

        public JsonResult UpdataCap(string contractVM)
        {
            contractVM = HttpUtility.UrlDecode(contractVM);
            ParturientContractVM contractVM1 = Newtonsoft.Json.JsonConvert.DeserializeObject<ParturientContractVM>(contractVM);
            //孕妇选择房间入住后
            //1 修改合同表房间id 入住时间 孕妇表合同id home表的入住状态
            //_contractService.UpdataContract(contractVM);
            _contractService.UpdataContract(contractVM1);
            //2生成服务任务表
            return Json(_serviceDoService.ServiceDoAdd(contractVM1.Cid));

        }
        //现金支付
        public JsonResult CashPay(ContractVM contractVM)
        {
            int contractId=contractVM.Id;
            // 付款金额 套餐+押金
            decimal depositAmount = Convert.ToDecimal(contractVM.PackagePrice);
            decimal packagePrice = Convert.ToDecimal(contractVM.Deposit);
            decimal totalAmount = depositAmount + packagePrice;
            Staff staff = Session["user"] as Staff;
            int sid = staff.Id;
            return Json(_contractService.PaySuccess(contractId, totalAmount, sid,1));
        }
        #endregion

    }
}